<?php
namespace home\controller;
use MongoDB\Client;
use MongoDB\Driver\Manager;
use IteratorIterator;

class MongodemoController extends HomeBaseController
{
    public $mongo_auth = null;
    public $collection = null;

    public function __construct()
    {
        parent::__construct();
        $mongodb_config = load_config('database','mongodb');

        $this->mongo_auth = 'mongodb://'.$mongodb_config['hostname'].':'.$mongodb_config['port'];

        $client = new \MongoDB\Client($this->mongo_auth, []);
        $db = $client->selectDatabase($mongodb_config['database']);
        $this->collection  = $db->selectCollection("mod_smart_title");

    }

    //查找操作
    public function listAction()
    {
        /**按照ObjectId查找
        //默认的_id是对象类型，不能直接传字符串
        $mongo_id = new \MongoDB\BSON\ObjectId('5d510a576def05881600002d');
        $select_result = $collection->findOne(['_id' => $mongo_id]);
        */
        //按照batch_number的数值5246698572414_5442252513675_1_0_1565592149
        $select_result = $this->collection->findOne(['batch_number' =>'5246698572414_5442252513675_1_0_1565592149']);
        $select_result = (array)$select_result->getArrayCopy();
        $_id = ((array)$select_result['_id'])['oid'];
        $title =  $select_result['title'];

        echo $title;
        echo "<hr>";
        $con    = new \MongoDB\Driver\Manager($this->mongo_auth);
        //模拟分页，跳过第一页的5条,按照创建时间倒序
        $options = [
            'skip' => 1*5,
            'limit'=> 5,
            'sort' =>['create_time'=>-1]
        ];
        $query  = new \MongoDB\Driver\Query(['uid' => '5246698572414'],$options);
        $cursor = $con->executeQuery('AutoTemplate.mod_smart_title',$query);
        $it     = new IteratorIterator($cursor);
        $it->rewind();
        while ($doc=$it->current()) {
            $doc = (array)$doc;
            debug_print(((array)$doc['_id'])['oid'],0);
            debug_print($doc,0);
            $it->next();
            echo '<hr>';
        }

    }

    //添加操作
    public function addAction()
    {
        $insertOneResult = $this->collection->insertOne([
            'username' => 'admin',
            'email' => 'admin@example.com',
            'name' => 'Admin User',
        ]);

        echo '<hr>';
        printf("Inserted %d document(s)\n", $insertOneResult->getInsertedCount());
        echo '<hr>';
        //这个是对象形式的
        var_dump($insertOneResult->getInsertedId());
        echo '<hr>';
        $insert_result = (array)$insertOneResult->getInsertedId();
        $insert_id = $insert_result['oid'];
        //字符串形式
        var_dump($insert_id);
        echo '<hr>';
        exit;
        $insertManyResult = $this->collection->insertMany([
            [
                'username' => 'admin',
                'email' => 'admin@example.com',
                'name' => 'Admin User',
            ],
            [
                'username' => 'test',
                'email' => 'test@example.com',
                'name' => 'Test User',
            ],
        ]);

        printf("Inserted %d document(s)\n", $insertManyResult->getInsertedCount());
        echo '<hr>';
        var_dump($insertManyResult->getInsertedIds());

    }

    //更新操作
    public function updateAction()
    {

        $this->collection->insertOne(['name' => 'Bob', 'state' => 'ny']);
        $this->collection->insertOne(['name' => 'Alice', 'state' => 'ny']);
        //只更新1个
        $updateResult = $this->collection->updateOne(
            ['state' => 'ny'],
            ['$set' => ['country' => 'us']]
        );

        printf("Matched %d document(s)\n", $updateResult->getMatchedCount());
        printf("Modified %d document(s)\n", $updateResult->getModifiedCount());

        $this->collection->insertOne(['name' => 'Jim', 'state' => 'ny']);
        $this->collection->insertOne(['name' => 'Jim', 'state' => 'ny']);
        //更新多个
        $updateResult = $this->collection->updateMany(
            ['name' => 'Jim'],
            ['$set' => ['state' => 'jp']]
        );
        printf("Matched %d document(s)\n", $updateResult->getMatchedCount());
        printf("Modified %d document(s)\n", $updateResult->getModifiedCount());

    }

    //删除操作
    public function deleteAction()
    {
        $this->collection->insertOne(['name' => 'LiLei', 'state' => 'ny']);
        $this->collection->insertOne(['name' => 'LiLei', 'state' => 'ny']);
        //只删除1个
        $deleteResult = $this->collection->deleteOne(
            ['name' => 'LiLei']
        );
        echo '<hr>';
        printf("Deleted %d document(s)\n", $deleteResult->getDeletedCount());
        echo '<hr>';
        $this->collection->insertOne(['name' => 'Luxi', 'state' => 'ny']);
        $this->collection->insertOne(['name' => 'Luxi', 'state' => 'ny']);
        //删除多个
        $deleteResult = $this->collection->deleteMany(
            ['name' => 'Luxi']
        );
        printf("Deleted %d document(s)\n", $deleteResult->getDeletedCount());
        echo '<hr>';
    }
}